//
//  MainViewController.swift
//  KitchenAssistant
//
//  Created by 陈燕璇 on 2021/3/28.
//

import UIKit

class MainViewController: UITabBarController {
    // MARK: - 监听方法
    /// 点击撰写按钮
    /// 如果`单纯`使用 `private` 运行循环将无法正确发送消息，导致崩溃
    /// 如果使用 @objc 修饰符号，可以保证运行循环能够发送此消息，即使函数被标记为 private
    @objc private func clickComposedButton() {
        print("点我了")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        addChildViewControllers()
        setupComposedButton()
    }
    // MARK: - 懒加载控件
    private lazy var composedButton: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")
    
    override func viewWillAppear(_ animated: Bool) {
        // 会创建 tabBar 中的所有控制器对应的按钮！
        super.viewWillAppear(animated)
        // 将撰写按钮弄到最前面
        tabBar.bringSubviewToFront(composedButton)
    }
}
    extension MainViewController {
    //设置编写按钮
    private func setupComposedButton(){
            // 1. 添加按钮
            tabBar.addSubview(composedButton)
            // 2. 调整按钮
            let count = children.count
            print(count)
            // 让按钮宽一点点，能够解决手指触摸的容错问题
            let w = tabBar.bounds.width / CGFloat(count) - 1
            
        composedButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        // 3. 添加监听方法
        composedButton.addTarget(self, action: #selector(self.clickComposedButton), for: .touchUpInside)
    }
    /// 添加所有的控制器
    private func addChildViewControllers() {
        //设置图片渲染颜色
        tabBar.tintColor = UIColor.orange
        addChildViewController(vc: HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(vc: MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChild(UIViewController())
        addChildViewController(vc: DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(vc: ProfileTableViewController(), title: "我的", imageName: "tabbar_profile")
    }
    //添加控制器
    private func addChildViewController(vc: UIViewController,title:String, imageName:String) {
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: vc)
        addChild(nav)
        
    }
}
